package com.study.mike.common.utils;


import org.springframework.util.Base64Utils;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.util.Arrays;
import java.util.Base64;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author kh
 */
public class AesUtil {

    private static final String KEY_ALGORITHM = "AES";
    /**
     * 默认的加密算法
     */
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";

    /**
     * 自定义密码
     */
    private static final String PASS_WORD = "officemate";
    private static SecretKeySpec AES_PASSWORD;

    /**
     * AES 加密操作
     *
     * @param content  待加密内容
     * @return 返回Base64转码后的加密数据
     */
    public static String encrypt(String content) {
        try {
            // 创建密码器
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            byte[] byteContent = content.getBytes("utf-8");
            // 初始化为加密模式的密码器
            cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(PASS_WORD));
            // 加密
            byte[] result = cipher.doFinal(byteContent);
            //通过Base64转码返回
            return Base64.getEncoder().encodeToString(result);
        } catch (Exception ex) {
            Logger.getLogger(AesUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    /**
     * AES 解密操作
     *
     * @param content
     * @return
     */
    public static String decrypt(String content) {
        try {
            //实例化
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            //使用密钥初始化，设置为解密模式
            cipher.init(Cipher.DECRYPT_MODE, getSecretKey(PASS_WORD));
            //执行操作
            byte[] result = cipher.doFinal(Base64Utils.decodeFromString(content));
            return new String(result, "utf-8");
        } catch (Exception ex) {
            ex.printStackTrace();
            Logger.getLogger(AesUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    /**
     * 生成加密秘钥
     *
     * @return
     */
    private static SecretKeySpec getSecretKey(String password) throws Exception {
        //返回生成指定算法密钥生成器的 KeyGenerator 对象
        if (AES_PASSWORD != null) {
            return AES_PASSWORD;
        }
        try {  //返回生成指定算法密钥生成器的 KeyGenerator 对象
            byte[] keyBytes = Arrays.copyOf(password.getBytes("ASCII"), 16);
            // 转换为AES专用密钥
            AES_PASSWORD = new SecretKeySpec(keyBytes, KEY_ALGORITHM);
            return AES_PASSWORD;
        } catch (Exception ex) {
            throw new Exception("加密秘钥失败");
        }

    }
}

